import React from "react";
import GoBack from "@/components/TheGoBack";
import { Form, Select, Input, InputNumber } from "antd";
import TheUpload from "../../../../components/TheUpload";
import Sku from "./Sku";
import "../../style/style.less";
import TheButton from "../../../../components/TheButton";
import TheQuill from "@/components/TheQuill";
import _ from 'lodash';
import { apiGetCalssify, apiProductInfoInsert, apiProductInfoUpdateState } from '@/request/commodity'

class Add extends React.Component {
  state = {
    currentIndex: 1,
    skuPropertyArray: [],
    skuPropertyTable: [],
    skuType: "",
    numResult: [],
    options: [],
    productTxt: ''
  };
  async componentDidMount() {
    await this.getClassifyList()
  }
  getClassifyList = async () => {
    let res = await apiGetCalssify()
    let options = res.data.map(v => {
      return {
        label: v.productClassifyName,
        value: v.productClassifyId
      }
    })
    this.setState({
      options
    })
  }
  getFileResult = (value) => {
    if (value.length && value[0].response && value[0].response.code === 0) {
      const id = value[0].response.data;
      this.formRef.setFieldsValue({ productShowImages: id });
    } else {
      this.formRef.setFieldsValue({ productShowImages: "" });
    }
  };
  /**
   * @desc 设置新闻内容表单默认值
   * */
  setNewsContent = (data) => {
    this.setState({
      productTxt: data
    })
  };
  setCurrentIndex = async (index) => {
    let status = true
    await this.formRef.validateFields().catch(err => {
      status = false
    })
    let productInfoJson = this.formRef.getFieldsValue()
    productInfoJson.originalPrice = React.$transNum(productInfoJson.originalPrice, 0, 2)
    productInfoJson.currentPrice = React.$transNum(productInfoJson.currentPrice, 0, 2)
    this.setState({
      productInfoJson
    })
    let { skuPropertyArray, skuPropertyTable, skuType, numResult } = this.state
    numResult = numResult && numResult.length && numResult.map(v => {
      return {
        ...v,
        isChecked: false,
      }
    })
    if (!status) {
      status = false
      return React.$message({
        type: 'info',
        content: '参数信息为必填信息'
      })
    }
    const productSkuJson = JSON.stringify({ skuPropertyTable, numResult, skuPropertyArray })
    const findEmpty = value => {
      value.forEach(v => {
        delete v.isChecked
        // if (!_.every(v)) {
        //   status = false
        // }
        if (!v.skuOriginalPrice) {
          status = false
        }
        if (!v.skuCurrentPrice) {
          status = false
        }
        // if (!v.stock) {
        //   status = false
        // }
        if (!v.imageFile) {
          status = false
        }
        if (!v.propCodeArray) {
          status = false
        }
      })
      return status
    }
    skuPropertyArray.forEach(v => {
      if (!v.name) {
        return status = false
      }
    })
    if (!status) {
      return React.$message({
        type: 'info',
        content: '规格标题不能为空'
      })
    }
    if (!numResult) {
      return React.$message({
        type: 'info',
        content: '请填写完整的SKU信息'
      })
    }

    if (!findEmpty(numResult)) {
      return React.$message({
        type: 'info',
        content: '请填写完整的SKU信息'
      })
    }
    numResult = numResult.map(v => {
      return {
        ...v,
        skuOriginalPrice: React.$transNum(v.skuOriginalPrice, 0, 2),
        skuCurrentPrice: React.$transNum(v.skuCurrentPrice, 0, 2)
      }
    })
    // let materialId = numResult.map(v => _.toString(v.materialId))
    // let uniqmaterialId = _.uniq(materialId)
    // if (_.size(materialId) !== _.size(uniqmaterialId)) {
    //   return React.$message({
    //     type: 'info',
    //     content: '物料ID不能相同'
    //   })
    // }
    let material = /^[A-Za-z0-9]+$/;
    let flag = false
    let con = false
    let arr1 = numResult.reduce((pre, cur, index) => {
      // console.log(pre, cur);
      if (pre.includes(cur.materialId) && cur.materialId) {
        flag = true
        return pre
      }
      console.log(cur.materialId);
      console.log(material.test(cur.materialId));
      if(cur.materialId){
        if(!material.test(cur.materialId)){
          con = true
        }
      }
      pre.push(cur.materialId)
      return pre
    }, [])
    if(con){
      return React.$message({
        type: 'info',
        content: '物料ID只能为字母和数字'
      })
    }
    if (flag) {
      return React.$message({
        type: 'info',
        content: '物料ID不能相同'
      })
    }
    let propCodeArray = numResult.map(v => _.toString(v.propCodeArray))
    let uniqCodeArray = _.uniq(propCodeArray)
    if (_.size(propCodeArray) !== _.size(uniqCodeArray)) {
      return React.$message({
        type: 'info',
        content: '编码不能相同'
      })
    }
    let productStock = numResult.map(v => {
      return v.stock
    })
    productStock = _.sum(productStock)
    let arr = []
    if (numResult.length === 1) {
      if (skuPropertyTable[0].length > 1) {
        arr = _.zip(skuPropertyTable, numResult)
      } else {
        if (Array.prototype.isPrototypeOf(skuPropertyTable[0])) {
          arr = _.zip(skuPropertyTable[0], numResult)
        } else {
          let table = _.flatten(skuPropertyTable)
          arr = _.zip(table, numResult)
        }
      }
    } else {
      if (skuPropertyTable.length !== numResult.length) {
        arr = _.zip(_.flatten(skuPropertyTable), numResult)
      } else {
        arr = _.zip(skuPropertyTable, numResult)
      }
    }
    const skuInfo = arr.map((v, i) => {
      let skuAttribute = null
      let b = null
      if (Array.prototype.isPrototypeOf(v[0])) {
        skuAttribute = v[0].map((v, i) => {
          return {
            key: v.name,
            value: v.itemName
          }
        })
      } else if (Object.prototype.isPrototypeOf(v[0])) {
        skuAttribute = [
          {
            key: v[0].name,
            value: v[0].itemName
          }
        ]
      }
      if (Object.prototype.isPrototypeOf(v[1])) {
        b = v[1]
      }
      // delete b.isChecked
      return {
        ...b,
        skuAttribute,
      }
    })
    this.setState({
      skuInfoJson: JSON.stringify(skuInfo),
      productSkuJson,
      productStock
    })

    if (status)
      this.setState({ currentIndex: index });
  };
  /**
   * @desc 获取sku返回值
   * */
  getSkuProperty = (skuPropertyArray, skuPropertyTable, skuType) => {
    let arr = [];
    if (skuPropertyTable.length > 0) {
      if (
        Object.prototype.toString.call(skuPropertyTable[0]) ===
        "[object Object]"
      ) {
        skuPropertyTable.forEach((v) => {
          arr.push(v);
        });
        arr = [arr];
      } else {
        arr = skuPropertyTable;
      }
    }
    this.setState({ skuPropertyArray, skuPropertyTable: arr, skuType });
  };
  /**
   * @desc 获取sku价格返回值
   * */
  getNumResult = (numResult) => {
    this.setState({ numResult });
  };
  goback = () => {
    this.props.history.go(-1);
  };
  onSubmit = async () => {
    this.setState({ btnLoading: true })
    if (this.state.currentIndex === 2) {
      if (!this.state.productTxt) {
        this.setState({ btnLoading: false })
        return React.$message({
          type: 'info',
          content: '商品规格信息为必填信息'
        })
      } else {
        let { productInfoJson, productSkuJson, productTxt, skuInfoJson, productStock } = this.state
        productInfoJson = JSON.stringify({ ...productInfoJson, productSkuJson, productTxt, productStock })
        let res = await apiProductInfoInsert({ productInfoJson, skuInfoJson })
        if (res.code === 0) {
          let response = await apiProductInfoUpdateState({ productId: res.data, reviewStatus: 'S' })
          if (response.code === 0) {
            React.$message({
              type: 'info',
              content: '新商品发布成功'
            })
            this.props.history.goBack()
          }
        }
      }
    }
    this.setState({ btnLoading: false })
  }
  onSave = async () => {
    this.setState({ btnLoading: true })
    if (this.state.currentIndex === 2) {
      if (!this.state.productTxt) {
        this.setState({ btnLoading: false })
        return React.$message({
          type: 'info',
          content: '商品规格信息为必填信息'
        })
      } else {
        let { productInfoJson, productSkuJson, productTxt, skuInfoJson, productStock } = this.state
        productInfoJson = JSON.stringify({ ...productInfoJson, productSkuJson, productTxt, productStock })
        let res = await apiProductInfoInsert({ productInfoJson, skuInfoJson })
        if (res.code === 0) {
          React.$message({
            type: 'info',
            content: '新商品保存成功'
          })
          this.props.history.goBack()
        }
      }
    }
    this.setState({ btnLoading: false })
  }
  render() {
    const { currentIndex, btnLoading } = this.state;
    return (
      <div className="p-layout-box commodity-list-add">
        <GoBack history={this.props.history} title={"新增商品"} />
        <div className="content">
          <div style={{ display: currentIndex === 1 ? "block" : "none" }}>
            <div>
              <div className="title">基本信息</div>
              <div className="form-box">
                <Form ref={ref => this.formRef = ref}>
                  <Form.Item label="商品分类" name={'productClassifyId'} rules={[{ required: true }]}>
                    <Select placeholder="请选择商品分类" options={this.state.options} allowClear/>
                  </Form.Item>
                  <Form.Item label="商品名称" name={'productName'} rules={[{ required: true }, { max: 100 }, { whitespace: true }]}>
                    <Input placeholder="请输入商品名称" />
                  </Form.Item>
                  <Form.Item label="商品原价" name={'originalPrice'} rules={[{ required: true }, {
                    pattern: /^\d+(\.\d{0,2})?$/,
                    message: '只能输入正数且最多两位小数'
                  }]}>
                    <InputNumber max={10000000} min={0.01} placeholder="请输入商品原价" />
                  </Form.Item>
                  <Form.Item label="商品现价" name={'currentPrice'} rules={[{ required: true }, {
                    pattern: /^\d+(\.\d{0,2})?$/,
                    message: '只能输入正数且最多两位小数'
                  }]}>
                    <InputNumber max={10000000} min={0.01} placeholder="请输入商品现价" />
                  </Form.Item>
                  <Form.Item label="商品图片" name={'productShowImages'} rules={[{ required: true }]}>
                    <TheUpload getFileResult={this.getFileResult} len={1} />
                  </Form.Item>
                </Form>
              </div>
            </div>
            <div>
              <div className="title">商品规格信息</div>
              <Sku
                getSkuProperty={this.getSkuProperty}
                getNumResult={this.getNumResult}
              />
            </div>
          </div>
          <div style={{ display: currentIndex === 2 ? "block" : "none" }}>
            <div className="title">商品规格信息</div>
            <div style={{ width: '90%', margin: 'auto' }}>
              <TheQuill style={{ height: 500 }} defaultValue={" "} setNewsContent={this.setNewsContent} />
            </div>
          </div>
        </div>
        <div className="button-group">
          <TheButton type="default" size="middle" onClick={this.goback}>
            取消
          </TheButton>

          {currentIndex === 1 && (
            <TheButton
              style={{ backgroundColor: "#F59A23", color: "#fff" }}
              size="middle"
              onClick={() => this.setCurrentIndex(2)}
            >
              下一页
            </TheButton>
          )}

          {currentIndex === 2 && (
            <div>
              <TheButton
                type="default"
                size="middle"
                onClick={() => this.setCurrentIndex(1)}
              >
                上一步
              </TheButton>
              <TheButton
                style={{ backgroundColor: "#F59A23", color: "#fff" }}
                size="middle"
                onClick={this.onSubmit}
                loading={btnLoading}
              >
                发布
              </TheButton>
              <TheButton
                style={{ backgroundColor: "#F59A23", color: "#fff" }}
                size="middle"
                onClick={this.onSave}
                loading={btnLoading}
              >
                保存
              </TheButton>
            </div>
          )}
        </div>
      </div>
    );
  }
}

export default Add;
